package com.zimmor.mq.rocket.base.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

/**
 * @Author:zimmor
 * @Date: 2021/11/18 14:52
 * @Description 异步发送消息
 * @version: 1.0.0
 */

public class AsyncProducer {
    public static void main(String[] args) throws Exception {
        //1.创建一个producer，并设置生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group2");
        //2.设置producer的namesrv地址
        producer.setNamesrvAddr("192.168.204.128:9876;192.168.204.129:9876");
        //3.启动producer
        producer.start();
//        producer.setRetryTimesWhenSendAsyncFailed(0);
        //4.新建消息对象，设置topic，tag，消息体
        for (int i = 0; i < 5; i++) {
            Message message = new Message("base", "tag2", ("异步发送消息测试" + i).getBytes());
            //5.发送消息
            producer.send(message, new SendCallback() {
                public void onSuccess(SendResult sendResult) {
                    System.out.println("sendResult = " + sendResult);
                }

                public void onException(Throwable throwable) {
                    System.out.println("throwable = " + throwable);
                }
            });
        }
        TimeUnit.SECONDS.sleep(10);
        //6.关闭producer
        producer.shutdown();
    }
}
